Ext.BLANK_IMAGE_URL = "../script/ext-2.0.2/resources/images/default/s.gif";

var classNameTemp = new Ext.form.TextField({
    id: 'classNameTemp',
    name: 'userNameTemp',
    width: 100
});

var storeClassManage = new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
        url: 'children/paymentorder!list.action?dateTime=' + new Date().getTime()
    }),
    reader: new Ext.data.JsonReader({
        root: 'ZANY',
        totalProperty: "results",
        fields: ["name", "createTime", "creater", "id"]
    }),
    sortInfo: {field: 'harmDate', direction: 'DESC'},// 排序信息
    remoteSort: true
});

storeClassManage.load();

var sm = new Ext.grid.CheckboxSelectionModel();

var colClassManage = new Ext.grid.ColumnModel([sm,
    {header: "班级名称", dataIndex: "name", width: 10, sortable: true},
    {header: "创建时间", dataIndex: "createTime", width: 10, sortable: true,renderer:function (val) {
            if(val==''){
                return ''
            }
            return new Date(val).format("Y-m-d H:i:s");
        }},
    {header: "创建人", dataIndex: "creater", width: 10, sortable: true},
    {header: "ID", dataIndex: "id", width: 10, sortable: true, hidden: true}
]);

var oneTbar = new Ext.Toolbar({
    items: ['-', {text: '&nbsp;&nbsp;查&nbsp;&nbsp;询&nbsp;&nbsp;', iconCls: 'yes', handler: getList},
        '-', {text: '生成缴费', iconCls: 'add', handler: insertinfo},
        '-', {text: '&nbsp;&nbsp;删&nbsp;&nbsp;除&nbsp;&nbsp;', iconCls: 'remove', handler: delinfo}
    ]
});

var paramFristStore = new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({url: 'children/class!list.action?dateTime=' + new Date().getTime()}),
    reader: new Ext.data.JsonReader({
        root: 'ZANY',
        fields: ["id", "name"]
    }),
    remoteSort: true
});
paramFristStore.load();

var paramFrist = new Ext.form.ComboBox({
    id: 'paramFrist',
    name: 'paramFrist',
    fieldLabel: '班级',
    hiddenName: 'frist',
    store: paramFristStore,
    valueField: 'id',
    displayField: 'name',
    typeAhead: true,
    mode: 'local',
    triggerAction: 'all',
    resizable: true,
    emptyText: '请选择班级...',
    allowBlank: true,
    width: 150,
    forceSelection: false
});

var classManage = new Ext.grid.GridPanel({
    id: 'classManage',
    title: '[缴费管理]信息维护',
    height: 500,
    stripeRows: true,
    bodyStyle: 'width:100%',
    disableSelection: true,
    cm: colClassManage,
    viewConfig: {
        forceFit: true
    },
    store: storeClassManage,
    iconCls: 'details',
    animCollapse: true,
    trackMouseOver: false,
    loadMask: {msg: '正在加载[用户管理]信息，请稍侯……'},
    selModel: sm,
    tbar: ['-', new Ext.form.Label({text: '班级:'}), '-', paramFrist],
    listeners: {
        'render': function () {
            oneTbar.render(this.tbar); //add one tbar
        }
    },
    bbar: new Ext.PagingToolbar({
        pageSize: 20,
        store: storeClassManage,
        displayInfo: true,
        emptyMsg: '没有记录'
    })
});

function update() {
    if (Ext.getCmp("classManage").getSelectionModel().hasSelection()) {
        Ext.MessageBox.confirm('Message', '请问您真的要重置密码？', function (btn) {
            if (btn == 'yes') {
                var ids = new Array();
                var records = Ext.getCmp("classManage").getSelectionModel().getSelections();
                for (var i = 0, len = records.length; i < len; i++) {
                    ids[i] = records[i].data["userCode"];
                }
                Ext.Ajax.request({
                    url: 'userInfo!update.action?dateTime=' + new Date().getTime(),
                    params: {updateId: ids},
                    success: function (response, options) {
                        var response = Ext.util.JSON.decode(response.responseText);
                        if (response.success) {
                            ZANY.util.Msg('信息', "重置密码成功！");
                        } else if (!response.success) {
                            ZANY.util.Msg('信息', "重置密码失败，如有问题请联系系统管理员！");
                        }
                    }
                });
            }
        })
    } else {
        ZANY.util.Msg('提示信息', "请选择用户后再操作！");
    }
}

function delinfo() {
    if (Ext.getCmp("classManage").getSelectionModel().hasSelection()) {
        Ext.MessageBox.confirm('Message', '请问您真的要删除所选数据么？', function (btn) {
            if (btn == 'yes') {
                var ids = new Array();
                var records = Ext.getCmp("classManage").getSelectionModel().getSelections();
                for (var i = 0, len = records.length; i < len; i++) {
                    ids[i] = records[i].data["id"];
                }
                console.log(ids);
                Ext.Ajax.request({
                    url: 'children/class!delete.action?dateTime=' + new Date().getTime(),
                    params: {delId: ids},
                    success: function (response, options) {
                        var response = Ext.util.JSON.decode(response.responseText);
                        if (response.success) {
                            Ext.getCmp('classManage').getStore().reload(); //刷新Grid
                            ZANY.util.Msg('信息', "删除角色信息成功！");
                        } else if (!response.success) {
                            ZANY.util.Msg('信息', "删除角色信息失败，如有问题请联系系统管理员！");
                        }
                    }
                });
            }
        })
    } else {
        ZANY.util.Msg('提示信息', "请选择用户后再操作！");
    }
}

var fp = new Ext.FormPanel({
    id: 'ext_form',
    labelWidth: 100,
    waitMsg: '正在提交，请稍后...',
    frame: true,
    bodyStyle: 'padding:5px 5px 0',
    width: 400,
    reader: new Ext.data.JsonReader({
        root: 'ZANY',
        totalProperty: "results",
        fields: ["name"]
    }),
    items: [{
        layout: 'form',
        defaultType: 'textfield',
        items: [{
            fieldLabel: '班级名称',
            name: 'name',
            id: 'name',
            maxLength: 10,
            anchor: '95%',
            allowBlank: false
        }, new Ext.form.Hidden({name: 'id'}),
        ]
    }]
});


var storePaymentPManage = new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
        url: 'children/paymentproject!list.action?dateTime=' + new Date().getTime()
    }),
    reader: new Ext.data.JsonReader({
        root: 'ZANY',
        totalProperty: "results",
        fields: ["name", "id"]
    }),
});


var smPayment = new Ext.grid.CheckboxSelectionModel();

// storePaymentPManage.addListener('load',function(){
//     // var records=[];//存放选中记录
//     for(var i=0;i<storePaymentPManage.getCount();i++){
//         var record = storePaymentPManage.getAt(i);
//         // alert(record)
//         // if(record.data.lcss==0){//根据后台数据判断那些记录默认选中
//         //     records.push(record);
//         // }
//     }
//     // sm.selectRecords(records);//执行选中记录
//     // alert(1111)
// });

var colPaymentManage = new Ext.grid.ColumnModel([smPayment,
    {header: "缴费项目", dataIndex: "name", width: 10, sortable: true}
]);
storePaymentPManage.load();
var grid_tab = new Ext.grid.GridPanel({
    id: 'projectManage',
    iconCls: 'zoomIcon',
    border: false,
    viewConfig: {
        forceFit: true
    },
    loadMask: {msg: '正在查询数据,请稍候......'},
    selModel: smPayment,
    store: storePaymentPManage,
    cm: colPaymentManage
});

var winKey = new Ext.Window({
    id: "ext_win",
    title: '[选择缴费项目]',
    width: 400,
    closeAction: 'hide',
    modal: true,
    iconCls: 'add',
    buttons: [{
        text: '提交',
        handler: function () {

            var ids = new Array();
            var classs = new Array();
            var records = Ext.getCmp("classManage").getSelectionModel().getSelections();
            var projectRecords = Ext.getCmp("projectManage").getSelectionModel().getSelections();
            var classobj = {classid: ""}
            for (var i = 0, len = records.length; i < len; i++) {
                ids[i] = records[i].data["id"];
                classobj.classid = ids[i]
                classobj['projects'] = new Array()
                for (var j = 0; j < projectRecords.length; j++) {
                    var project_id = projectRecords[j].data['id']
                    classobj.projects.push(project_id)
                }
                classs.push(classobj)
            }
            var jsonStr = Ext.util.JSON.encode(classs)

            Ext.Ajax.request({
                method: 'POST',
                url: '../children/paymentorder!save.action',
                params: {
                    'data': jsonStr
                },
                success: function (response, config) {
                    var json = Ext.util.JSON.decode(response.responseText);
                    console.log(json)
                    if (json.success == true) {
                        // Ext.getCmp('menuGrid').getStore().reload();
                        Ext.Msg.alert("提示", '生成欠费记录成功!');
                        var model = grid_tab.getSelectionModel();
                        model.clearSelections();
                        winKey.hide();
                    } else {
                        Ext.Msg.alert('提示', '生成欠费记录失败!');
                        var model = grid_tab.getSelectionModel();
                        model.clearSelections();
                    }
                },
                failure: function () {
                    Ext.Msg.alert('提示', '生成欠费记录失败!');
                    var model = grid_tab.getSelectionModel();
                    model.clearSelections();
                    winKey.hide();
                }
            });
        }
    }, {
        text: '取消', handler: function () {
            winKey.hide();
        }
    }],
    items: [grid_tab]
});

function insertinfo() {
    winKey.show();
}

classManage.addListener('rowdblclick', function (e) {
        if (Ext.getCmp("classManage").getSelectionModel().hasSelection()) {
            getDetail();
        }
    }, classManage
);

function getDetail() {

    var records = Ext.getCmp("classManage").getSelectionModel().getSelected();
    var id = records.data["id"];
    var name = records.data["name"]
    winKey.show();
    //清空所有选择.
    var model = grid_tab.getSelectionModel();
    model.clearSelections();
    Ext.Ajax.request({
        method: 'GET',
        url: '../children/paymentorder!getProjectByClassId.action',
        params: {
            'classId': id
        },
        success: function (response, config) {
            var json = Ext.util.JSON.decode(response.responseText);
            var entity = json.ZANY
            var _records = new Array();
            for (var i = 0; i < entity.length; i++) {
                storePaymentPManage.each(function (record) {
                    if (record.data.id == entity[i].id)
                        _records.push(record)
                });
            }
            smPayment.selectRecords(_records, true);
        },
        failure: function () {
            Ext.Msg.alert('提示', '生成欠费记录失败!');
            var model = grid_tab.getSelectionModel();
            model.clearSelections();
        }
    });


}


function resetQuery() {
    Ext.getCmp("userNameTemp").setValue('');
    orgTree.setValue('');
}

function getList() {
    var params = {};
    if (paramFrist.getRawValue() == '') {
        paramFrist.clearValue()
    }
    var classId = paramFrist.getValue();
    params.classId = classId
    storeClassManage.baseParams = params;
    storeClassManage.load({
        callback: function (r, options, success) {
            if (success == false) {
                Ext.Msg.alert("错误", storeClassManage.reader.jsonData.msg);
            }
        }
    });
}

Ext.onReady(function () {
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
    var port = new Ext.Viewport({
        layout: 'fit',
        frame: true,
        items: [this.classManage]
    });
});